<?php define(CABLE_VERSION,'3.0.4'); ?>
<html>
	<head>
		<title>CABLE Setup</title>
		<link type="text/css" href="setup.css" rel="stylesheet" />
	</head>
	<body>
		<div id="setup_version">CABLE Setup.php, Version <?php echo CABLE_VERSION ?></div>
		<div id="setup_container">
<?php

/* check for empty globals */
if (!$_REQUEST['setup_sitename'])
	$_REQUEST['setup_sitename'] = '';

if (!$_REQUEST['setup_sitepath'])
	$_REQUEST['setup_sitepath'] = str_replace('setup.php','',$_ENV[SCRIPT_FILENAME]);
	
if (!$_REQUEST['setup_siteurl'])
	$_REQUEST['setup_siteurl'] = str_replace('setup.php','','http://'.$_ENV[SERVER_NAME].$_ENV[SCRIPT_NAME]);

if (!$_REQUEST['setup_dbserver'])
	$_REQUEST['setup_dbserver'] = 'localhost';
	
if (!$_REQUEST['setup_prefix'])
	$_REQUEST['setup_prefix'] = 'default';
	
if (!$_REQUEST['setup_theme'])
	$_REQUEST['setup_theme'] = 'bek_flat';

$error = false;
$done = false;
if (!file_exists('config.ini'))
{
	if ($_REQUEST['submit'])
	{
		if ($_REQUEST['setup_password1'] != $_REQUEST['setup_password2'])
			$error = 'Root user passwords do not match.';
		else
		{
			$messages = array('Running setup script.');
			if (($ret = checkFiles()) === true)
			{
				if (($ret = makeDbStuff()) === true)
				{
					if (($ret = makeConfig()) === true)
					{
						echo "<div id=\"setup_login\">\n";
						echo "Click [<a href=\"admin.php?action=login\">here</a>] to log in to CABLE.\n";
						echo "</div>\n";
						$messages[] = "Finished.";
						$done = true;
					}
					else
						$error = $ret;
				}
				else
					$error = $ret;
			}
			else
				$error = $ret;
		}
	}
}
else
{
	echo "<div id=\"setup_login\">\n";
	echo "Click [<a href=\"admin.php?action=login\">here</a>] to log in to CABLE.\n";
	echo "</div>\n";
	$done = true;
	return;
}

function checkFiles()
{
	global $messages;
	
	$sitepath = urldecode($_REQUEST['setup_sitepath']);
	
	/* is the directory writable? */
	if (!is_writable($sitepath))
		return "CABLE requires full read/write access to ".$_REQUEST['setup_sitepath'];
	
	/* check for the existence of required files */
	$files = array(
	'admin.php',
	'entry.php',
	'index.php',
	'search.php',
	'library/classes.php',
	'library/strings.php',
	'library/example.ini',
	'plugins/cable_admin_0.php',
	'plugins/cable_admin_1.php',
	'plugins/cable_admin_2.php',
	'plugins/cable_admin_3.php',
	'plugins/cable_admin_4.php',
	'plugins/cable_admin.plugin',
	'plugins/cable_admin.ini',
	'plugins/cable_entry.plugin',
	'plugins/cable_entry.ini',
	'plugins/cable_index.plugin',
	'plugins/cable_index.ini',
	'plugins/cable_search.plugin',
	'plugins/cable_search.ini',
	'themes/'.urldecode($_REQUEST['setup_theme'])
	);

	$messages[] = "Checking for required files/folders.";	
	foreach($files as $name)
		if (!file_exists($sitepath.$name))
			return "Required file/folder \"$name\" not found."; 
	
	/* make sure correct folders exist */
	$folders = array('caches'=>0700,'css'=>0755,'files'=>0755,'users'=>0755);
	foreach($folders as $name => $perms)
	{
		if (!file_exists($sitepath.$name))
		{
			if (mkdir($sitepath.$name,$perms))
				$messages[] = "Created directory ".$_REQUEST['setup_sitepath'].$name;
			else
				return "Could not create directory ".$_REQUEST['setup_sitepath'].$name;
		}
	}
	
	return true;
}
	
function makeDbStuff()
{
	global $messages;
	
	$messages[] = "Creating database elements.";
	
	/* attempt to connect to database */
	$server = urldecode($_REQUEST['setup_dbserver']);
	$user = urldecode($_REQUEST['setup_dbusername']);
	$password = urldecode($_REQUEST['setup_dbpassword']);
	$dbname = str_replace('"','',str_replace("'",'',urldecode($_REQUEST['setup_dbname'])));
	
	if (($db_link = mysql_connect($server,$user,$password)) === false)
		return "Error while connecting to database server: ".mysql_error();
	
	/* attempt to create database if it doesn't exist */
	if (mysql_select_db($dbname,$db_link) === false)
	{
		if (mysql_create_db($dbname,$db_link) === false)
			return "Error while creating database: ".mysql_error();
		$messages[] = "Created database \"$dbname\".";
	}
			
	/* check for existence of tables */
	$query = "SHOW TABLES FROM $dbname";
	if (($result = mysql_query($query,$db_link)) === false)
		return "Error accessing database: ".mysql_error();
	else
	{
		$tables = array();
		while (($row = mysql_fetch_row($result)) !== false)
			$tables[] = $row[0];
	}
	
	/* get prefix */
	if ($_REQUEST['setup_prefix'] != '')
		$prefix = '_'.preg_replace('/[\W]/','',urldecode($_REQUEST['setup_prefix'])).'_';
	else
		$prefix = '_';
	
	/* entry table creation */
	if (in_array('cable'.$prefix.'entries',$tables))
		$messages[] = "cable".$prefix."entries table already exists.";
	else
	{	
		$query = "CREATE TABLE IF NOT EXISTS cable".$prefix."entries (
timestamp bigint(20) NOT NULL,
author varchar(64) NOT NULL,
title varchar(255) NOT NULL,
text longtext NOT NULL,
data longtext,
visible tinyint(1) NOT NULL default '0',
PRIMARY KEY (timestamp)) ENGINE = MyISAM DEFAULT CHARSET = latin1;";
		if (mysql_query($query,$db_link) === false)
			return "Error creating cable".$prefix."entries table: ".mysql_error();
		$messages[] = "Created cable".$prefix."entries database table.";
	}

	/* template table creation */
	if (in_array('cable'.$prefix.'templates',$tables))
		$messages[] = "cable".$prefix."templates table already exists.";
	else
	{
		$query = "CREATE TABLE IF NOT EXISTS cable".$prefix."templates (
name char(64) NOT NULL,
theme varchar(64) NOT NULL,
template text NOT NULL,
current_version char(16) default NULL,
compatible_version varchar(16) NOT NULL default  '0.0.0',
author varchar(64)  default NULL,
PRIMARY KEY (name)) ENGINE = MyISAM DEFAULT CHARSET = latin1;";
		if (mysql_query($query,$db_link) === false)
			return "Error creating cable".$prefix."templates table: ".mysql_error();
		$messages[] = "Created cable".$prefix."templates database table.";
	}
	
	/* users table creation */
	if (in_array('cable'.$prefix.'users',$tables))
		$messages[] = "cable".$prefix."users table already exists.";
	else
	{
		$query = "CREATE TABLE IF NOT EXISTS cable".$prefix."users (
username varchar(255) NOT NULL,
fullname varchar(255) NOT NULL,
adminlevel tinyint(4) NOT NULL default '0',
email varchar(255) NOT NULL default '',
password varchar(255) NOT NULL default '',
data text,
PRIMARY KEY (username)) ENGINE = MyISAM DEFAULT CHARSET = latin1;";
 		if (mysql_query($query,$db_link) === false)
			return "Error creating cable".$prefix."users table: ".mysql_error();
		$messages[] = "Created cable".$prefix."users database table.";
	}
	
	/* insert root user */
	$username	= str_replace('"','',str_replace("'",'',urldecode($_REQUEST['setup_rootusername'])));
	$fullname	= str_replace('"','',str_replace("'",'',urldecode($_REQUEST['setup_rootfullname'])));
	$email		= str_replace('"','',str_replace("'",'',urldecode($_REQUEST['setup_rootemail'])));
	$password	= md5($username.urldecode($_REQUEST['setup_password1']));
	$query = "INSERT INTO cable".$prefix."users (username,fullname,adminlevel,email,password) VALUES('$username','$fullname',2,'$email','$password')";
	if (mysql_query($query,$db_link) === false)
		return "Error creating root user: ".mysql_error();
	$messages[] = "Created root user \"$username\".";
	
	$sitepath = urldecode($_REQUEST['setup_sitepath']);
	/* load selected theme */
	$theme = str_replace('"','',str_replace("'",'',urldecode($_REQUEST['setup_theme'])));
	$local = urldecode($_REQUEST['setup_sitepath']);
	if (is_dir($sitepath."themes/$theme/"))
	{
		$query = "SELECT COUNT(*) FROM cable".$prefix."templates WHERE (theme ='$theme') LIMIT 1";
		if(($result = mysql_query($query,$db_link)) !== false)
		{		
			$fail = false;
			/* check for the presence of the basic template files */
			if (!is_readable($sitepath."themes/$theme/index.tmpl"))
				$fail = 'index.tmpl';
			if (!is_readable($sitepath."themes/$theme/entry.tmpl"))
				$fail = 'entry.tmpl';
			if (!is_readable($sitepath."themes/$theme/admin.tmpl"))
				$fail = 'admin.tmpl';
			if (!is_readable($sitepath."themes/$theme/search.tmpl"))
				$fail = 'search.tmpl';
			
			if ($dir_handle = opendir($sitepath."themes/$theme/"))
			{
				if (($template_info = parse_ini_file($sitepath."themes/$theme/theme.ini")) === false)
					return "Could not read $theme theme.ini configuration file";
				else
					$messages[] = "Read $theme configuration file.";
				
				if (str_replace('.','',$template_info['Compatible']) < str_replace('.','',CABLE_VERSION))
					return 'This template is incompatible with this version of CABLE.';
					
				while(($file = readdir($dir_handle)) !== false)
				{
					$path_parts = pathinfo($sitepath."themes/$theme/$file");
					if ($path_parts['extension'] == 'tmpl') /* a template file */
					{
						if (is_readable($sitepath."themes/$theme/".$file))
						{
							$template = addslashes(file_get_contents($sitepath."themes/$theme/$file"));
							$query = "REPLACE INTO cable".$prefix."templates (name,theme,template,current_version,compatible_version,author) VALUES('".$path_parts['filename']."','".$theme."','".$template."','".$template_info['Version']."','".$template_info['Compatible']."','".$template_info['Author']."')";
							if(($result = mysql_query($query,$db_link)) === false)
								return "Error writing template file '$file' to template database.";
							$messages[] = "Wrote \"$theme\" template file \"$file\" to template database table.";
						}
						else
							return "Error reading template file \"".$sitepath."themes/$theme/$file\".";
					}
					elseif($path_parts['extension'] == 'css') /* a css file */
					{
						/* if the theme's folder doesn't exist in the css directory, create it */
						if (!file_exists($sitepath."css/$theme/"))
						{
							if (!mkdir($sitepath."css/$theme/"))
								return "Error creating $sitepath"."css/$theme/";
							$messages[] = "Created directory $sitepath"."css/$theme/";
						}
						
						/* copy it to the theme's folder in the css directory */
						if (!copy($sitepath."themes/$theme/$file",$sitepath."css/$theme/$file"))
							return "Error copying theme CSS file '$file'.";
						else
							$messages[] = "Copied \"$theme\" CSS file \"$file\" to \"$sitepath"."css/$theme/$file\"."; 
					}
					elseif((!is_dir($sitepath."themes/$theme/$file")) && ($file != 'theme.ini')) /* must be an image file */
					{
						/* if the theme's folder doesn't exist in the files directory, create it */
						if (!file_exists($sitepath."files/$theme"))
						{
							if (!mkdir($sitepath."files/$theme"))
								return "Error creating $sitepath"."files/$theme/.";
							$messages[] = "Created directory $sitepath"."/files/$theme/";
						}

						/* copy it to the theme's folder in the images directory */
						if (!copy($sitepath."themes/$theme/$file",$sitepath."files/$theme/$file"))
							return "Error copying theme file '$file'.";
						else
							$messages[] = "Copied \"$theme\" file \"$file\" to \"$sitepath"."files/$theme/$file\".";
					}
				}
			}
			else
				return 'Error opening template directory.';
		}
		else
			return 'Error reading template database table.';
	}
	else
		return "Error accessing template directory $sitepath".$theme;
		
	return true;
}

function makeConfig()
{
	global $messages;

	if (is_readable('./pre_config.ini'))
		$config_file = file_get_contents('./pre_config.ini');
	else
		return "Could not read pre_config.ini";
	
	$server = urldecode($_REQUEST['setup_dbserver']);
	$user = urldecode($_REQUEST['setup_dbusername']);
	$password = urldecode($_REQUEST['setup_dbpassword']);
	$dbname = str_replace('"','',str_replace("'",'',urldecode($_REQUEST['setup_dbname'])));
	
	/* do replacements */
	$config_file = str_replace('<DBSERVER>',$server,$config_file);
	$config_file = str_replace('<DBUSER>',$user,$config_file);
	$config_file = str_replace('<DBPASSWORD>',$password,$config_file);
	$config_file = str_replace('<DBNAME>',$dbname,$config_file);
	$config_file = str_replace('<PREFIX>',preg_replace('/[\W]/','',urldecode($_REQUEST['setup_prefix'])),$config_file);
	$config_file = str_replace('<SITENAME>',str_replace('"','',urldecode($_REQUEST['setup_sitename'])),$config_file);
	$config_file = str_replace('<SITEPATH>',str_replace('"','',urldecode($_REQUEST['setup_sitepath'])),$config_file);
	$config_file = str_replace('<SITEURL>',str_replace('"','',urldecode($_REQUEST['setup_siteurl'])),$config_file);
	$config_file = str_replace('<THEMENAME>',str_replace('"','',urldecode($_REQUEST['setup_theme'])),$config_file);
	if ($_REQUEST['setup_modrewrite'])
		$config_file = str_replace('<MODREWRITE>','1',$config_file);
	else
		$config_file = str_replace('<MODREWRITE>','0',$config_file);

	if (file_put_contents('config.ini',$config_file) === false)
		return "Could not write config file.";
	$messages[] = "Wrote site configuration to config.ini.";

	return true;
}

?>
			<form name="setup_form" action="" method="POST">
				<div id="setup_title">CABLE Setup</div>
				<?php
				if ($messages)
				{
					echo "<div id=\"setup_messages\">\n";
					foreach($messages as $i => $message)
						echo "<p>$i. $message</p>\n";
					echo "</div>\n";
				}
				
				if ($error !== false)
					echo "<div id=\"setup_error\">$error</div>\n";
					
				if ($done)
				{
					echo "</form>\n</div>\n</body>\n</html>";
					return;
				}
				?>
				<div class="option_section">
					General Settings
					<hr />
				</div>
				<div class="option_container">
					<div class="option_name">Site Name:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_sitename'] ?>" name="setup_sitename" size="30" /></div>
					<div class="option_notes">
						<p>Type here whatever the name of the site will be.</p>
					</div>
				</div>
				<div class="option_container">
					<div class="option_name">Site Path:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_sitepath'] ?>" name="setup_sitepath" size="30" /></div>
					<div class="option_notes">
						<p>This is the local path to CABLE installation's folder. Ex.: /home/username/www/cable/</p>
						<p>There must be a terminal slash (/) on the end of this path.</p>
					</div>
				</div>
				<div class="option_container">
					<div class="option_name">Site URL:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_siteurl'] ?>" name="setup_siteurl" size="30" /></div>
					<div class="option_notes">
						<p>This is the URL of the CABLE installation's folder. Ex.: http://www.somesite.com/cable/</p>
						<p>There must be a terminal slash (/) on the end of this url.</p>
					</div>
				</div>
				<div class="option_section">
					Database Settings
					<hr />
				</div>
				<div class="option_container">
					<div class="option_name">Database server:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_dbserver'] ?>" name="setup_dbserver" size="30" /></div>
					<div class="option_notes">
						<p>URL of the MySQL database server to use. ("localhost" if using local MySQL server.)</p>
					</div>
				</div>
				<div class="option_container">
					<div class="option_name">Database username:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_dbusername'] ?>" name="setup_dbusername" size="30" /></div>
					<div class="option_notes">
						<p>Username to use when logging into MySQL server. Cannot contain " or '.</p>
					</div>
				</div>
				<div class="option_container">
					<div class="option_name">Database password:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_dbpassword'] ?>" name="setup_dbpassword" size="30" /></div>
					<div class="option_notes">
						<p>Password to use when logging into MySQL server. Cannot contain " or '.</p>
					</div>
				</div>
				<div class="option_container">
					<div class="option_name">Database name:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_dbname'] ?>" name="setup_dbname" size="30" /></div>
					<div class="option_notes">
						<p>The name of the database CABLE will create the necessary tables (alphanumerics and underscore only). If this database doesn't exist, CABLE will attempt to create it.</p>
					</div>
				</div>
				<div class="option_container">
					<div class="option_name">Table prefix:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_prefix'] ?>" name="setup_prefix" size="30" /></div>
					<div class="option_notes">
						<p>The prefix cable will apply to all tables within the database for this installation (alphanumerics only). This allows multiple CABLE installations to use the same database. Leave blank for no prefix.</p>
					</div>
				</div>
				<div class="option_section">
					Miscellaneous
					<hr />
				</div>
				<div class="option_container">
					<div class="option_name">Theme name:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_theme'] ?>" name="setup_theme" size="30" /></div>
					<div class="option_notes">
						<p>Name of the default theme to load (may be changed later). Alphanumerics and underscores only.</p>
					</div>
				</div>
				<div class="option_container">
					<div class="option_name">Use ModRewrite:</div>
					<div class="option_value"><input type="checkbox" <?php if($_REQUEST['setup_modrewrite']){echo 'checked="checked"';} ?> name="setup_modrewrite" /></div>
					<div class="option_notes">
						<p>Use ModRewrite to rewrite ungainly URLs?</p>
					</div>
				</div>
				<div class="option_section">
					Administration
					<hr />
				</div>
				<div class="option_container">
					<div class="option_name">Root username:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_rootusername'] ?>" name="setup_rootusername" size="30" /></div>
					<div class="option_notes">
						<p>Username (login) for the root user (will be used to log in for further settings after installation).</p>
					</div>
				</div>
				<div class="option_container">
					<div class="option_name">Root user full name:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_rootfullname'] ?>" name="setup_rootfullname" size="30" /></div>
					<div class="option_notes">
						<p>The full name of the root user.</p>
					</div>
				</div>
				<div class="option_container">
					<div class="option_name">Root user email:</div>
					<div class="option_value"><input type="text" value="<?php echo $_REQUEST['setup_rootemail'] ?>" name="setup_rootemail" size="30" /></div>
					<div class="option_notes">
						<p>The email address for the root user (used to email lost password).</p>
					</div>
				</div>
				<div class="option_container">
					<div class="option_name">Root user passwords:</div>
					<div class="option_value">
						<input type="password" name="setup_password1" value="<?php echo $_REQUEST['setup_password1'] ?>" size="10" />
						<br />(confirm)<br />
						<input type="password" name="setup_password2" value="<?php echo $_REQUEST['setup_password2'] ?>" size="10" />
					</div>
					<div class="option_notes">
						<p>Password for the root user.</p>
					</div>
				</div>
				<div class="option_section">
					Submission
					<hr />
				</div>
				<div id="setup_submit"><input type="submit" name="submit" value="Run Setup Script" /></div>
			</form>
		</div>
	</body>
</html>
